package com.atguigu.alice;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author alice
 * @date 2021/10/27
 * @apiNote
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
//        read();
//        write();
        testTransferFrom();
    }

    private static void read() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("D:\\text\\01.txt","rw");
        FileChannel channel = accessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(48);
        int bytesRead = channel.read(buffer);
        while (bytesRead!=-1){
            System.out.println("读取："+bytesRead);
            buffer.flip();
            while (buffer.hasRemaining()){
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            bytesRead = channel.read(buffer);
        }
        accessFile.close();
        System.out.println("操作结束");
    }

    public static void write() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("D:\\text\\01.txt", "rw");
        FileChannel channel = accessFile.getChannel();
        String newData = "hello world"+System.currentTimeMillis();
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        byteBuffer.clear();
        byteBuffer.put(newData.getBytes());
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()){
            channel.write(byteBuffer);
        }
        channel.close();
    }

    public static void testTransferFrom() throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("D:\\text\\a.txt","rw");
        FileChannel fromChannel = aFile.getChannel();
        RandomAccessFile bFile = new RandomAccessFile("D:\\text\\b.txt","rw");
        FileChannel toChannel = bFile.getChannel();

        fromChannel.truncate(1);
        long position = 0;
        long count = fromChannel.size();
        long position1 = fromChannel.position();
        toChannel.transferFrom(fromChannel,position,count);

        aFile.close();
        bFile.close();
        System.out.println("over!");

    }
}
